package ability

import (
	"os"
	"path/filepath"
	"sjy/customcmd/src/constants"
	"sjy/customcmd/src/entity"
	"sjy/customcmd/src/event"
	"sjy/customcmd/src/utils"
	"strings"
)

var CustomCmdInstance = FuncManager.Register(
	&CustomCmdClass{
		FuncObjBase: &FuncObjBase{
			ClassName: constants.CustomCmd.Code,
		},
	},
)

var CustomCmdDefaultConfig = &entity.CustomCmdConfig{
	CmdName: "up",
	Task:    "help",
}

type CustomCmdClass struct {
	*FuncObjBase
}

func (r *CustomCmdClass) Execute(obj *FuncEntity) {
	config := getCustomCmdConfig()
	if config.CmdName != obj.Paramenter.OrgArgs[0] {
		r.msg(obj)
		return
	}

	if config.Task == constants.CustomCmd.Code {
		HelpInstanse.Execute(obj)
		return
	}

	funcClass := FuncManager.FindFunc(config.Task)
	if funcClass == nil {
		HelpInstanse.Execute(obj)
		return
	}
	funcClass.Execute(obj)
}

func (r *CustomCmdClass) msg(obj *FuncEntity) {
	_p, _ := os.Executable()
	fileNameWithExt := filepath.Base(_p)
	fileNameWithoutExt := fileNameWithExt[:len(fileNameWithExt)-len(filepath.Ext(fileNameWithExt))]
	utils.Info("没有找到命令：%s", fileNameWithoutExt+" "+strings.Join(obj.Paramenter.OrgArgs, " "))
}

func getCustomCmdConfig() *entity.CustomCmdConfig {
	result := event.GetConfig(func(obj *entity.MainConfig) entity.FieldInterface {
		return obj.CustomCmd
	})
	config, ok := result.(*entity.CustomCmdConfig)
	if ok && config != nil && !config.AllEmpty() {
		return config
	} else {
		return CustomCmdDefaultConfig
	}
}
